import { cloudbaseApp, development } from '@/cloudbaseapi/cloudbase-api'
const db = cloudbaseApp().database()
const $ = db.command.aggregate
const _ = db.command
const { HYDBNAME, HYTYPE } = development()

/**
 * 获取诗集列表
 * @param limit
 * @param page
 * @param filterStr
 * @returns {Promise<GetRes>}
 */
export async function getHyItem(limit, page, type = '全部类型') {
  const skip = (page - 1) * limit
  let where = { type }
  if(type == '全部类型') {
    delete where['type']
  }
  const count = await db.collection(HYDBNAME).where(where).count()
  const total = count.total
  const items = await db.collection(HYDBNAME).where(where).limit(limit).skip(skip).orderBy('sort', 'desc').get()
  items['total'] = total
  return items
}
/**
 * 通过id值查询话语内容
 */
export function getHyId(id) {
  return db.collection(HYDBNAME).doc(id).get()
}

/**
 * 获取话语类型
 * @returns {Promise<cloudbase.database.GetRes>}
 */
export function getHyType() {
  return db.collection(HYTYPE).get()
}
export function update(data, isEdit) {
  const newData = { ...data }
  const id = newData['_id']
  delete newData['_id']
  delete newData['_openid']
  return new Promise((resolve, reject) => {
    if (!isEdit) {
      db.collection(HYDBNAME)
        .where({ type: data.type })
        .orderBy('sort', 'desc')
        .limit(1)
        .get()
        .then(res => {
          newData['sort'] = res.data[0]['sort'] + 1
          db.collection(HYDBNAME).doc(id).get().then(resC => {
            if (resC.data.length > 0) {
              reject(new Error('您提交的信息已经有了'))
            } else {
              db.collection(HYDBNAME).doc(id).set(newData).then(res => {
                resolve(res)
              }).catch(err => {
                reject(err)
              })
            }
          })
        })
    } else {
      db.collection(HYDBNAME).doc(id).set(newData).then(res => {
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    }
  })

}
export function del(id) {
  return db.collection(HYDBNAME).doc(id).remove()
}
